package demo.blog.controller;


import demo.blog.config.shiro.PasswordHelper;
import demo.blog.controller.vo.UserEnrollVo;
import demo.blog.model.User;
import demo.blog.service.UserService;
import demo.blog.util.Result;
import javafx.beans.binding.StringBinding;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/login")
    //BindingResult br 需紧跟Valid后
    public Result login(@RequestBody @Valid User user, BindingResult br){
        Result result=valid(br);
        if(result!=null) return result;
        /*if(!userVo.getCaptcha().equals(request.getSession().getAttribute("captcha"))){
            return new Result(0,"验证码错误！");
        }*/
        // 1.获取Subject
        Subject subject = SecurityUtils.getSubject();
        // 2.封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(user.getEmail(), user.getPassword());
        try{
            // 3.执行登录方法
            subject.login(token);
        }catch (Exception e){
            return new Result(0,"账号或密码错误");
        }
        subject.getSession().setTimeout(60*5);
        user = userService.getUserByEmail(user.getEmail());
        System.out.println(user);
        subject.getSession().setAttribute("userSession",user.getId());
        return new Result(1,"登陆成功!");
    }
    @PostMapping("/enroll")
    public Result enroll(@RequestBody @Valid UserEnrollVo userEnrollVo, BindingResult br){
        Result result=valid(br);
        if(result!=null) return result;

        String inviteCode = "427";
        if(!inviteCode.equals(userEnrollVo.getInvite())){
            return  new Result(0,"邀请码不对!");
        }

        User user = userEnrollVo.toUser();
        if(userService.getUserByEmail(user.getEmail())!=null){
            return new Result(0,"该用户已注册！");
        }
        new PasswordHelper().encryptPassword(user);
        user.setRoleId(1);
        user.setCreateDate(new Date().toString());
        user.setDelete(false);
        userService.addUser(user);
        return new Result(1,"注册成功！");
    }

    private Result valid(BindingResult result){
        if(result.hasErrors()){
            StringBuilder builder = new StringBuilder();
            for (FieldError error : result.getFieldErrors()){
                builder.append(error.getDefaultMessage()+"<br/>");
            }
            return new Result(0,builder.toString());
        }else{
            return null;
        }
    }
}

